package m.jclecai.com.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.internal.LoadingLayout;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.activity.LotteryPayActivity;
import m.jclecai.com.activity.LotteryProtocolActivity;
import m.jclecai.com.adapter.BettingConfirmAdapter;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.IssueInfoBean;
import m.jclecai.com.constant.Constant_Result;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.contents.LotteryType;
import m.jclecai.com.inter.OnCautionDialogConfirmListener;
import m.jclecai.com.inter.OnResultCallback;
import m.jclecai.com.inter.OnResultListener;
import m.jclecai.com.utils.BaseUtils;
import m.jclecai.com.utils.KlpkUtils;
import m.jclecai.com.utils.MakeRandomUtil;
import m.jclecai.com.utils.OkHttpClientManager;
import m.jclecai.com.utils.ToastUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.view.CautionDialog;

/**
 * Created by hp on 2017/4/5.
 * 投注确认
 */

public class BetConfirmActivity extends BaseActivity implements View.OnClickListener, TextWatcher, AdapterView.OnItemClickListener {
    @BindView(R.id.iv_pull_bg)
    ImageView ivPullBg;
    private TextView tv_term;
    private TextView tv_date;
    PullToRefreshListView ptrLisview;
    private ListView lv_betting_confirm;
    private BettingConfirmAdapter adapter;
    private IssueInfoBean bean;
    private CountDownTimer timer;
    String[] str = new String[]{"大", "小", "单", "双"};
    //和值
    String[] sumValue = new String[]{"3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"};
    String[] sumBonus = new String[]{"中240元", "中80元", "中40元", "中25元", "中16元", "中12元", "中10元", "中9元", "中9元", "中10元",
            "中12元", "中16元", "中25元", "中40元", "中80元", "中240元"};
    //三相同
    String[] threeSame = new String[]{"111", "222", "333", "444", "555", "666"};
    //二相同
    String[] twoSame = new String[]{"112", "113", "114", "115", "116", "221", "223", "224", "225", "226", "331", "332", "334", "335", "336",
            "441", "442", "443", "445", "446", "551", "552", "553", "554", "556", "661", "662", "663", "664", "665"};
    //三不同
    String[] threeDifferent = new String[]{"123", "124", "125", "126", "134", "135", "136", "145", "146", "156", "234", "235", "236", "245",
            "246", "256", "345", "346", "356", "456"};
    //二不同
    String[] twoDifferent = new String[]{"12", "13", "14", "15", "16", "23", "24", "25", "26", "34", "35", "36", "45", "46", "56"};
    //彩种
    private String type;
    //随机个数
    private int number;
    //球
    private ArrayList<String> ballNumber;
    //玩法及模式
    private ArrayList<String> mode;
    //注数及金额
    private ArrayList<String> numMoney;
    //总金额
    private int totalMoney;
    //总注数
    private int totalNum;
    //倍数
    private int multiple = 1;
    //期数
    private int num = 1;
    //传递给服务器的球信息
    private StringBuffer strBuffer;


    private String m;

    private TextView tv_number_money;
    private CheckBox cb_add_to;
    private TextView tv_add_to;
    private EditText et_multiple;
    private EditText et_num;
    private Button bt_bottom_left;
    private boolean isMultipleMode;
    private String[] money;

    @Override
    public int getContentView() {
        return R.layout.betting_confirm_activity;
    }

    @Override
    protected void initView() {
        setTitle("投注确认");
        leftOptionText("");
        rightOptionText("发起合买");
        tv_term = (TextView) findViewById(R.id.tv_term);
        tv_date = (TextView) findViewById(R.id.tv_date);

        tv_add_to = (TextView) findViewById(R.id.tv_add_to);
        cb_add_to = (CheckBox) findViewById(R.id.cb_add_to);

        TextView tv_back = (TextView) findViewById(R.id.tv_back);
        tv_back.setOnClickListener(this);

        et_num = (EditText) findViewById(R.id.et_num);
        et_num.addTextChangedListener(this);
        et_multiple = (EditText) findViewById(R.id.et_multiple);
        et_multiple.addTextChangedListener(this);

        Button bt_random_one = (Button) findViewById(R.id.bt_random_one);
        bt_random_one.setOnClickListener(this);
        Button bt_continue_select = (Button) findViewById(R.id.bt_continue_select);
        bt_continue_select.setOnClickListener(this);
        Button bt_random_five = (Button) findViewById(R.id.bt_random_five);
        bt_random_five.setOnClickListener(this);

        Button bt_confirm = (Button) findViewById(R.id.bt_confirm);
        bt_confirm.setOnClickListener(this);

        bt_bottom_left = (Button) findViewById(R.id.bt_bottom_left);
        tv_number_money = (TextView) findViewById(R.id.tv_number_money);

        //协议
        TextView tv_treaty = (TextView) findViewById(R.id.tv_treaty);
        tv_treaty.setOnClickListener(this);
        //是否勾选同意协议
        CheckBox cb_agree = (CheckBox) findViewById(R.id.cb_agree);
        ptrLisview = (PullToRefreshListView) findViewById(R.id.lv_betting_confirm);
//      ptrLisview.getLoadingLayoutProxy().setLoadingDrawable(ContextCompat.getDrawable(this, R.color.transparent));
        ptrLisview.getLoadingLayoutProxy().setPullLabel("下拉机选一注");
        ptrLisview.getLoadingLayoutProxy().setReleaseLabel("下拉机选一注");
        ptrLisview.getLoadingLayoutProxy().setRefreshingLabel("下拉机选一注");
        ptrLisview.setPullScrollListener(new PullToRefreshBase.OnPullScrollListener() {
            @Override
            public void scroll(int value, ViewGroup mHeaderLayout,
                               ViewGroup mFooterLayout) {
                int height = Math.abs(value) + 20;
                if (ptrLisview != null && ptrLisview.getState() ==
                        PullToRefreshBase.State.REFRESHING)
                    height += ((LoadingLayout) mHeaderLayout).getContentSize();
                if (ptrLisview != null && ptrLisview.getState() ==
                        PullToRefreshBase.State.RESET && value == 0)
                    height = 0;
                ((FrameLayout.LayoutParams) ivPullBg.getLayoutParams()).height = height;
                ivPullBg.requestLayout();
            }
        });
        ptrLisview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                ptrLisview.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        randomSelect(type, 1);
                    }
                }, 200);
            }
        });
        lv_betting_confirm = ptrLisview.getRefreshableView();
        View inflate = View.inflate(this, R.layout.lottery_list_footer, null);
        inflate.findViewById(R.id.betting_item_footer_clear).setOnClickListener(this);
        inflate.findViewById(R.id.betting_item_footer_check).setOnClickListener(this);
        lv_betting_confirm.addFooterView(inflate);
        adapter = new BettingConfirmAdapter(this, new OnResultListener() {
            @Override
            public void onReturnResult(String str) {
                totalNum = Integer.parseInt(str);
                setNumberMoney();
            }
        });

        findViewById(R.id.iv_date_unfold).setVisibility(View.GONE);
    }

    @Override
    protected void initData() {
        execData(getIntent());
        lv_betting_confirm.setAdapter(adapter);
        lv_betting_confirm.setOnItemClickListener(this);
        getIssueInfo(type);
    }

    void execData(Intent intent) {
        type = intent.getStringExtra("type");
        totalMoney += intent.getIntExtra("totalMoney", 0); //总金额
        totalNum += intent.getIntExtra("totalNum", 0);   //总注数
        if (ballNumber != null)
            ballNumber.addAll(intent.getStringArrayListExtra("ballNumber"));
        else
            ballNumber = intent.getStringArrayListExtra("ballNumber"); //球
        if (mode != null)
            mode.addAll(intent.getStringArrayListExtra("mode"));
        else
            mode = intent.getStringArrayListExtra("mode"); //玩法
        number += intent.getIntExtra("number", 0); //随机球个数
        if (numMoney != null)
            numMoney.addAll(intent.getStringArrayListExtra("numMoney"));
        else
            numMoney = intent.getStringArrayListExtra("numMoney"); //注数及金额

        //获取上级页面传递来的彩种最后一个玩法，用作机选判断
        if (mode.get(mode.size() - 1).contains(" ")) {
            m = mode.get(mode.size() - 1).substring(0, mode.get(mode.size() - 1).length() - 3);
        } else {
            m = mode.get(mode.size() - 1);
        }

        Log.e(TAG, "totalNum=" + totalNum);
        Log.e(TAG, "totalMoney=" + totalMoney);
        setNumberMoney();

        switch (BaseUtils.stringOfInt(type)) {
            case LotteryType.CQSSC:
            case LotteryType.SYXW:
            case LotteryType.SDXYXW:
            case LotteryType.GDSYXW:
            case LotteryType.ZJSYXW:
            case LotteryType.JSSYXW:
                //11选5才有盈利追号
                isMultipleMode();
                if (!isMultipleMode) {
                    String[] split = numMoney.get(0).split(" ");
                    Log.i(TAG, "split=" + split[1]);
                    money = split[1].split("元");
                    bt_bottom_left.setVisibility(View.VISIBLE);
                    bt_bottom_left.setOnClickListener(this);
                }
                break;
        }

        //大乐透有追加
        if (type.equals("dlt")) {
            cb_add_to.setVisibility(View.VISIBLE);
            tv_add_to.setVisibility(View.VISIBLE);

            cb_add_to.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    setNumberMoney();
                }
            });
        }
        adapter.setData(ballNumber, mode, numMoney);
    }

    //合买
    @OnClick(R.id.tv_right_option)
    void jointPurchase() {


        new AlertDialog.Builder(this)
                .setMessage("功能开发中...")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).show();

     /*   Log.e(TAG, "totalNum=" + totalNum);
        Log.e(TAG, "multiple=" + multiple);
        Log.e(TAG, "totalMoney=" + totalMoney);
        Log.e(TAG, "num=" + num);
        Log.e(TAG, "type=" + type);
        Log.e(TAG, "codes=" + formatCode());
        if (ballNumber.size() < 1) {
            ToastUtil.showToast(this, "请至少选择一注");
            return;
        }

        Intent intent = new Intent(this, JointPurchaseActivity.class);
        intent.putExtra("totalNum", totalNum);
        intent.putExtra("multiple", multiple);
        intent.putExtra("totalMoney", totalNum * 2 * multiple);   //这里总共的钱，不能算上连续追期的金钱；
        intent.putExtra("num", 1);
        intent.putExtra("type", type);
        intent.putExtra("codes", formatCode());
        startActivity(intent);*/

    }

    String substring;

    //拼接玩法对应的后缀使其符合投注要求
    private String formatCode() {
        strBuffer = new StringBuffer();
        for (int i = 0; i < mode.size(); i++) {
            if (mode.get(i).contains(" ")) {
                substring = mode.get(i).substring(0, mode.get(i).length() - 3);
            } else {
                substring = mode.get(i);
            }

            //========获取code==============;
            if ("klpk".equals(type)) {

                //做一些快乐扑克的公共的操作；
                String selectedNumbers = ballNumber.get(i);
                String[] selectedNumberArr = selectedNumbers.split(" ");

                String pokers = "";
                //这里我们进行的一个操作就是拼接字符串；
                List<String> indexTypeList = Arrays.asList(KlpkUtils.indexType);
                int index = indexTypeList.indexOf(substring);
                int pokerModeIndex = index < 5 ? index : 5;
                String[] pokerTypes = KlpkUtils.pokerType[pokerModeIndex];
                List<String> pokerTypeList = Arrays.asList(pokerTypes);
                for (int j = 0; j < selectedNumberArr.length; j++) {
                    //这里我们要做的一个操作就是将selectedNumberArr中的数据解析出来；
                    String selectedNumber = selectedNumberArr[j];
                    //得到pokerType在数组中的索引；
                    int pokerTypeIndex = pokerTypeList.indexOf(selectedNumber);
                    //这里对数据进行一个拼装；
                    if (pokerTypeIndex < 10) {
                        //我们需要将
                        pokers += "0" + pokerTypeIndex + " ";
                    } else {
                        pokers += pokerTypeIndex + " ";
                    }
                }
                pokers = pokers.trim();

                //快乐扑克的逻辑走在这里面...我们判断一下这里的逻辑；
                if ("对子".equals(substring)) {
                    strBuffer.append(pokers + LotteryType.KLPK_DZ);
                } else if ("同花".equals(substring)) {
                    strBuffer.append(pokers + LotteryType.KLPK_TH);
                } else if ("顺子".equals(substring)) {
                    strBuffer.append(pokers + LotteryType.KLPK_SZ);
                } else if ("同花顺".equals(substring)) {
                    strBuffer.append(pokers + LotteryType.KLPK_THS);
                } else if ("豹子".equals(substring)) {
                    strBuffer.append(pokers + LotteryType.KLPK_BZ);
                } else if ("任选一".equals(substring)) {
                    strBuffer.append(pokers + LotteryType.KLPK_RX1);
                } else if ("任选二".equals(substring)) {
                    strBuffer.append(pokers + LotteryType.KLPK_RX2);
                } else if ("任选三".equals(substring)) {
                    strBuffer.append(pokers + LotteryType.KLPK_RX3);
                } else if ("任选四".equals(substring)) {
                    strBuffer.append(pokers + LotteryType.KLPK_RX4);
                } else if ("任选五".equals(substring)) {
                    strBuffer.append(pokers + LotteryType.KLPK_RX5);
                } else if ("任选六".equals(substring)) {
                    strBuffer.append(pokers + LotteryType.KLPK_RX6);
                }

            } else if ((type.equals("pls") || type.equals("sd")) && substring.equals("直选和值")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.FC3D_HZ);
            } else if ("gdklsf".equals(type)) {
                //这里的话，我们要做的就是快乐十分的将数据拼装发送给服务器中；
                if ("选一数投".equals(substring)) {
                    strBuffer.append(ballNumber.get(i) + LotteryType.GDKLSF_XYST);
                } else if ("选一红投".equals(substring)) {
                    strBuffer.append(ballNumber.get(i) + LotteryType.GDKLSF_XYHT);
                } else if ("任选二".equals(substring)) {
                    strBuffer.append(ballNumber.get(i) + LotteryType.GDKLSF_RX2);
                } else if ("任选三".equals(substring)) {
                    strBuffer.append(ballNumber.get(i) + LotteryType.GDKLSF_RX3);
                } else if ("任选四".equals(substring)) {
                    strBuffer.append(ballNumber.get(i) + LotteryType.GDKLSF_RX4);
                } else if ("任选五".equals(substring)) {
                    strBuffer.append(ballNumber.get(i) + LotteryType.GDKLSF_RX5);
                } else if ("选二连组".equals(substring)) {
                    strBuffer.append(ballNumber.get(i) + LotteryType.GDKLSF_XELZU);
                } else if ("选二连直".equals(substring)) {
                    strBuffer.append(ballNumber.get(i) + LotteryType.GDKLSF_XELZHI);
                }
            } else if (substring.equals("任选二")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.RX2);
            } else if (substring.equals("任选三")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.RX3);
            } else if (substring.equals("任选四")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.RX4);
            } else if (substring.equals("任选五")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.RX5);
            } else if (substring.equals("任选六")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.RX6);
            } else if (substring.equals("任选七")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.RX7);
            } else if (substring.equals("任选八")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.RX8);
            } else if (substring.equals("前一直选")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.zhi1);
            } else if (substring.equals("前二直选")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.zhi2);
            } else if (substring.equals("前三直选")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.zhi3);
            } else if (substring.equals("前二组选")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.zu2);
            } else if (substring.equals("任选二胆拖")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.RX2_DT);
            } else if (substring.equals("任选三胆拖")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.RX3_DT);
            } else if (substring.equals("任选四胆拖")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.RX4_DT);
            } else if (substring.equals("任选五胆拖")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.RX5_DT);
            } else if (substring.equals("任选六胆拖")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.RX6_DT);
            } else if (substring.equals("任选七胆拖")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.RX7_DT);
            } else if (substring.equals("任选八胆拖")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.RX8_DT);
            } else if (substring.equals("前二组选胆拖")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.zu2_DT);
            } else if (substring.equals("前三组选胆拖")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.zu3_DT);
            } else if (substring.equals("前三组选")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.zu3);
            } else if (substring.equals("大乐透")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.SSQ_DLT);
            } else if (substring.equals("双色球")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.SSQ_DLT);
            } else if (substring.equals("七星彩")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.BASE);
            } else if (substring.equals("一星直选")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.SSC_YXZX);
            } else if (substring.equals("二星直选")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.SSC_EXZX);
            } else if (substring.equals("三星直选")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.SSC_SXZX);
            } else if (substring.equals("五星直选")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.SSC_WXZX);
            } else if (substring.equals("五星通选")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.SSC_WXTX);
            } else if (substring.equals("二星组选")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.SSC_EXZUX);
            } else if (substring.equals("组选三")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.SSC_ZU3);
            } else if (substring.equals("组选六")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.SSC_ZU6);
            } else if (substring.equals("大小单双")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.SSC_DXDS);
            } else if (substring.equals("直选")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.FC3D_ZHI1);
            } else if (substring.equals("组三单式")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.FC3D_ZU3DS);
            } else if (substring.equals("组三复式")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.FC3D_ZU3FS);
            } else if (substring.equals("组六")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.FC3D_ZU6);
            } else if (substring.equals("排列五")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.BASE);
            } else if (substring.equals("和值")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.KS_HZ);
            } else if (substring.equals("三同号")) {
                if (ballNumber.get(i).equals("三同号通选")) {
                    strBuffer.append(LotteryType.KS_STHTX);
                } else {
                    String[] split = ballNumber.get(i).split(",");
                    for (int k = 0; k < split.length; k++) {
                        strBuffer.append(split[k] + LotteryType.KS_STHDX);
                    }
                }
            } else if (substring.equals("二同号")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.KS_ETHDX);
            } else if (substring.equals("三不同号")) {
                if (ballNumber.get(i).contains(",")) {
                    String[] split = ballNumber.get(i).split(",");
                    for (int k = 0; k < split.length; k++) {
                        StringBuffer str = new StringBuffer();
                        str.append(split[k].substring(0, 1) + ",");
                        str.append(split[k].substring(1, 2) + ",");
                        str.append(split[k].substring(2, 3));
                        strBuffer.append(str + LotteryType.KS_SBTH);
                    }
                } else {
                    StringBuffer str = new StringBuffer();
                    String s = ballNumber.get(i);
                    str.append(s.substring(0, 1) + ",");
                    str.append(s.substring(1, 2) + ",");
                    str.append(s.substring(2, 3));
                    strBuffer.append(str + LotteryType.KS_SBTH);
                }
            } else if (substring.equals("二不同号")) {
                if (ballNumber.get(i).contains(",")) {
                    String[] split = ballNumber.get(i).split(",");
                    for (int k = 0; k < split.length; k++) {
                        StringBuffer str = new StringBuffer();
                        str.append(split[k].substring(0, 1) + ",");
                        str.append(split[k].substring(1, 2));
                        strBuffer.append(str + LotteryType.KS_EBTH);
                    }
                } else {
                    StringBuffer str = new StringBuffer();
                    String s = ballNumber.get(i);
                    str.append(s.substring(0, 1) + ",");
                    str.append(s.substring(1, 2));
                    strBuffer.append(str + LotteryType.KS_EBTH);
                }
            } else if (substring.equals("三同号通选")) {
                strBuffer.append(LotteryType.KS_STHTX);
            } else if (substring.equals("二同号复选")) {
                strBuffer.append(ballNumber.get(i) + LotteryType.KS_ETHFX);
            } else if (substring.equals("三连号通选")) {
                strBuffer.append(LotteryType.KS_SLHTX);
            }
        }
        return strBuffer.toString();
    }

    private void getIssueInfo(String type) {
        OkHttpClientManager.Param Url = new OkHttpClientManager.Param("url", Constant_Url.ISSUE_INFO);
        OkHttpClientManager.Param Type = new OkHttpClientManager.Param("type", type);
        OkHttpClientManager.Param[] param = new OkHttpClientManager.Param[]{Url, Type};
        try {
            OkHttpClientManager.getInstance().asynPost(new OnResultCallback() {
                @Override
                public void onGetResult(String json) {
                    IssueInfoBean bean = FastOk.get(json, IssueInfoBean.class);
                    setViewInfo(bean);
                }

                @Override
                public void onError() {
                    ToastUtil.showToast(BetConfirmActivity.this, R.string.connect_failure);
                }
            }, param);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void setViewInfo(IssueInfoBean bean) {
        if (bean == null) return;
        this.bean = bean;
        String term = bean.getTermNo();
        //获取当前时间

        String str = term.substring(term.length() - 2, term.length());
        tv_term.setText("距" + str + "期截止");
        startCountDownTime(Integer.parseInt(bean.getDeadLine()), str);

    }

    private void startCountDownTime(long time, final String str) {
        timer = new CountDownTimer(time * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

                tv_date.setText(BaseUtils.formatDateLineToString(millisUntilFinished));
            }

            @Override
            public void onFinish() {
                tv_date.setText("已截止");
//                getIssueInfo(type);
                timer.cancel();
            }
        };
        timer.start();// 开始计时
    }


    //判断是否有多个玩法，单一玩法才有追号，但是单复式，是属于同一个玩法；
    private void isMultipleMode() {
        String s = mode.get(0);

        //这里有可能是，任选六 单式，任选六 复式；
        String[] str = s.split(" ");
        if (str != null & str.length > 1) {
            s = str[0];
        }

        for (int i = 0; i < mode.size(); i++) {
            if (mode.get(i).contains(s)) {
                isMultipleMode = false;
            } else {
                isMultipleMode = true;//多个玩法
                break;
            }
        }
    }

    //继续选号
    private void continueSelect() {
        Intent intent = new Intent();
        intent.putStringArrayListExtra("ballNumber", ballNumber);
        intent.putStringArrayListExtra("mode", mode);
        intent.putStringArrayListExtra("numMoney", numMoney);
        intent.putExtra("totalMoney", totalMoney);
        intent.putExtra("totalNum", totalNum);
        setResult(0, intent);
        this.finish();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_continue_select: //继续选号
                continueSelect();
                break;
            case R.id.bt_random_one: //机选1注
                randomSelect(type, 1);
                break;
            case R.id.bt_random_five://机选5注
                randomSelect(type, 5);
                break;
            case R.id.bt_confirm://投注
                if (ballNumber.size() >= 1) {
                    showBuyInfo();
                } else {
                    ToastUtil.showToast(this, "请至少选择一注");
                }
                break;
            //智能追号,
            case R.id.bt_bottom_left:
                String code = formatCode();
                if (TextUtils.isEmpty(code)) {
                    DisPlay("请至少选择一注");
                    return;
                }
                Intent intent = new Intent(this, ContinuousBuyActivity.class);
                intent.putExtra("totalNum", totalNum);
                intent.putExtra("type", type);
                intent.putExtra("mode", m);
                intent.putExtra("totalMoney", totalNum * 2);
                intent.putExtra("code", code);
                startActivity(intent);
                break;
            //协议
            case R.id.tv_treaty:
                ToastUtil.showToast(this, "跳转协议");
                break;
            case R.id.tv_back:
                showCautionDialog();
                break;
            case R.id.betting_item_footer_clear:
                CautionDialog CautionDialog = new CautionDialog(this, "是否清除本次选号", new OnCautionDialogConfirmListener() {
                    @Override
                    public void onCancelListener() {
                    }

                    @Override
                    public void onConfirmListener() {
                        ballNumber.clear();
                        mode.clear();
                        numMoney.clear();
                        adapter.notifyDataSetChanged();
                    }
                });
                CautionDialog.show();

                break;
            case R.id.betting_item_footer_check:
                startActivity(LotteryProtocolActivity.getIntent(this));
                break;
        }
    }

    private void showBuyInfo() {
        Log.e(TAG, "code=" + formatCode());
        Log.e(TAG, "totalMoney=" + totalMoney);
        Log.e(TAG, "totalNum=" + totalNum);
        Log.e(TAG, "multiple=" + multiple);
        /**
         * 此处提交之前先判断用户是否登录
         */
        Intent intent = new Intent(this, LotteryPayActivity.class);
        intent.putExtra(PAY_VOTENUMS, String.valueOf(totalNum));
        intent.putExtra(PAY_MULTIPLE, String.valueOf(multiple));
        intent.putExtra(PAY_MONEY, String.valueOf(totalMoney));
        String code = formatCode();
        intent.putExtra(PAY_CODES, code.substring(0, code.length() - 1));   //这里的这个操作是去除，最后一个分号；
        intent.putExtra(PAY_TYPE, type);
        intent.putExtra(PAY_NAME, "自购");
        intent.putExtra(PAY_NUM, String.valueOf(num));
        if (cb_add_to.isChecked()) {
            intent.putExtra(PAY_LOTTERY_ADDTIONAL, "1");
        }
        if (bean != null)
            intent.putExtra(PAY_TERM, BaseUtils.strNoNull(bean.getTermNo()));
        startActivityForResult(intent, Constant_Result.CLOSEPAGE);
        Log.e("num", num + "_" + num);
    }

    //发回广播让来源界面去实现机选 然后本界面同步数据源
    private void randomSelect(String type, int count) {
        if (mode != null && mode.size() > 0 && mode.get(mode.size() - 1).contains("胆")) {
            //胆拖没有机选
            DisPlay("胆拖玩法不支持机选");
            if (ptrLisview != null)
                ptrLisview.onRefreshComplete();
            return;
        }
        Intent intent = new Intent(Constant_Result.RANDOMLOTTERYNUM);
        intent.putExtra("num", count);//机选几注
        sendBroadcast(intent);
//        randomSelect(type, count, 0);
    }

    //机选(因为某些彩种的价格逻辑未全部处理所以弃用)
    @Deprecated
    private void randomSelect(String type, int count, int p) {
        Log.i(TAG, "机选type=" + type);
        Log.i(TAG, "number=" + number);
        StringBuffer stringBuffer = null;
        StringBuffer stringBlueBuffer = null;
        switch (BaseUtils.stringOfInt(type)) {
            case LotteryType.SYXW:
            case LotteryType.SDXYXW:
                Log.i(TAG, "11选5");
                for (int j = 0; j < count; j++) {
                    stringBuffer = new StringBuffer();
                    if (m.equals("前二直选")) {
                        LinkedList<String> randomBall = MakeRandomUtil.getBall(11, 2);
                        for (int i = 0; i < randomBall.size(); i++) {
                            if (i == randomBall.size() - 1) {
                                stringBuffer.append(randomBall.get(i));
                            } else {
                                stringBuffer.append(randomBall.get(i) + "|");
                            }
                        }
                    } else if (m.equals("前三直选")) {
                        LinkedList<String> randomBall = MakeRandomUtil.getBall(11, 3);
                        for (int i = 0; i < randomBall.size(); i++) {
                            if (i == randomBall.size() - 1) {
                                stringBuffer.append(randomBall.get(i));
                            } else {
                                stringBuffer.append(randomBall.get(i) + "|");
                            }
                        }
                    } else {
                        if (m.contains("胆拖")) {
                            LinkedList<String> randomBall = MakeRandomUtil.getBall(11, number);
                            for (int i = 0; i < randomBall.size(); i++) {
                                if (i == 0) {
                                    stringBuffer.append(randomBall.get(i) + "$");
                                } else if (i == randomBall.size() - 1) {
                                    stringBuffer.append(randomBall.get(i));
                                } else {
                                    stringBuffer.append(randomBall.get(i) + " ");
                                }
                            }
                            mode.add(m);
                            numMoney.add((number - 1) + "注" + ((number - 1) * 2) + "元");
                            ballNumber.add(stringBuffer.toString());
                            totalNum += (number - 1);

                        } else {
                            LinkedList<String> randomBall = MakeRandomUtil.getBall(11, number);
                            for (int i = 0; i < randomBall.size(); i++) {
                                if (i == randomBall.size() - 1) {
                                    stringBuffer.append(randomBall.get(i));
                                } else {
                                    stringBuffer.append(randomBall.get(i) + " ");
                                }
                            }
                            if (!m.contains("单式") && !m.contains("复式"))
                                m += " 单式";
                            mode.add(m);
                            numMoney.add("1注 2元");
                            ballNumber.add(stringBuffer.toString());
                            totalNum++;
                        }
                    }
                }
                break;
            case LotteryType.SSQ:
                Log.i(TAG, "双色球");
                for (int j = 0; j < count; j++) {
                    stringBuffer = new StringBuffer();
                    stringBlueBuffer = new StringBuffer();
                    LinkedList<String> randomRedBall = MakeRandomUtil.getBall(33, 6);
                    LinkedList<String> randomBlueBall = MakeRandomUtil.getBall(16, 1);
                    //红球
                    for (int i = 0; i < randomRedBall.size(); i++) {
                        if (i == randomRedBall.size() - 1) {
                            stringBuffer.append(randomRedBall.get(i));
                        } else {
                            stringBuffer.append(randomRedBall.get(i) + ",");
                        }
                    }
                    //蓝球
                    for (int i = 0; i < randomBlueBall.size(); i++) {
                        if (i == randomBlueBall.size() - 1) {
                            stringBlueBuffer.append(randomBlueBall.get(i));
                        } else {
                            stringBlueBuffer.append(randomBlueBall.get(i) + ",");
                        }
                    }
                    ballNumber.add(stringBuffer.toString() + "|" + stringBlueBuffer.toString());
                    if (!m.contains("单式") && !m.contains("复式"))
                        m += " 单式";
                    mode.add(m);
                    numMoney.add("1注 2元");
                    totalNum++;
                }
                break;
            case LotteryType.DLT:
                Log.i(TAG, "大乐透");
                for (int j = 0; j < count; j++) {
                    stringBuffer = new StringBuffer();
                    stringBlueBuffer = new StringBuffer();
                    LinkedList<String> randomRedBall = MakeRandomUtil.getBall(35, 5);
                    LinkedList<String> randomBlueBall = MakeRandomUtil.getBall(12, 2);
                    //红球
                    for (int i = 0; i < randomRedBall.size(); i++) {
                        if (i == randomRedBall.size() - 1) {
                            stringBuffer.append(randomRedBall.get(i));
                        } else {
                            stringBuffer.append(randomRedBall.get(i) + ",");
                        }
                    }
                    //蓝球
                    for (int i = 0; i < randomBlueBall.size(); i++) {
                        if (i == randomBlueBall.size() - 1) {
                            stringBlueBuffer.append(randomBlueBall.get(i));
                        } else {
                            stringBlueBuffer.append(randomBlueBall.get(i) + ",");
                        }
                    }
                    ballNumber.add(stringBuffer.toString() + "|" + stringBlueBuffer.toString());
                    if (!m.contains("单式") && !m.contains("复式"))
                        m += " 单式";
                    mode.add(m);
                    numMoney.add("1注 2元");
                    totalNum++;
                }
                break;
            case LotteryType.QLC:
                Log.i(TAG, "七乐彩");
                for (int j = 0; j < count; j++) {
                    stringBuffer = new StringBuffer();
                    LinkedList<String> randomRedBall = MakeRandomUtil.getBall(30, 7);
                    for (int i = 0; i < randomRedBall.size(); i++) {
                        if (i == randomRedBall.size() - 1) {
                            stringBuffer.append(randomRedBall.get(i));
                        } else {
                            stringBuffer.append(randomRedBall.get(i) + ",");
                        }
                    }
                    ballNumber.add(stringBuffer.toString());
                    if (!m.contains("单式") && !m.contains("复式"))
                        m += " 单式";
                    mode.add(m);
                    numMoney.add("1注 2元");
                    totalNum++;
                }
                break;
            case LotteryType.SD:
            case LotteryType.PLS:
            case LotteryType.QXC:
            case LotteryType.PLW:
                for (int j = 0; j < count; j++) {
                    stringBuffer = new StringBuffer();
                    LinkedList<String> randomBall = MakeRandomUtil.getWeiBall(10, number);
                    for (int i = 0; i < randomBall.size(); i++) {
                        if (i == randomBall.size() - 1) {
                            stringBuffer.append(randomBall.get(i));
                        } else {
                            stringBuffer.append(randomBall.get(i) + ",");
                        }
                    }
                    ballNumber.add(stringBuffer.toString());
                    if (!m.contains("单式") && !m.contains("复式"))
                        m += " 单式";
                    mode.add(m);
                    numMoney.add("1注 2元");
                    totalNum++;
                }
                break;
            //重庆时时彩
            case LotteryType.CQSSC:
                if (m.equals("大小单双")) {
                    for (int j = 0; j < count; j++) {
                        stringBuffer = new StringBuffer();
                        LinkedList<String> randomBall1 = MakeRandomUtil.getBall(4);
                        LinkedList<String> randomBall2 = MakeRandomUtil.getBall(4);

                        stringBuffer.append(str[Integer.parseInt(randomBall1.get(0))] + ",");
                        stringBuffer.append(str[Integer.parseInt(randomBall2.get(0))]);

                        ballNumber.add(stringBuffer.toString());
                        mode.add(m);
                        numMoney.add("1注 2元");
                        totalNum++;
                    }
                } else {
                    for (int j = 0; j < count; j++) {
                        stringBuffer = new StringBuffer();
                        LinkedList<String> randomBall = MakeRandomUtil.getWeiBall(10, number);

                        for (int i = 0; i < randomBall.size(); i++) {
                            if (i == randomBall.size() - 1) {
                                stringBuffer.append(randomBall.get(i));
                            } else {
                                stringBuffer.append(randomBall.get(i) + ",");
                            }
                        }
                        ballNumber.add(stringBuffer.toString());
                        if ("组选三".equals(m)) {
                            mode.add(m);
                            numMoney.add("2注 4元");
                            totalNum += 2;
                        } else {
                            mode.add(m);
                            numMoney.add("1注 2元");
                            totalNum++;
                        }
                    }
                }
                break;
            case LotteryType.JSKS:
                if (m.equals("和值")) {
                    LinkedList<String> randomOne = MakeRandomUtil.getBall(6);
                    LinkedList<String> randomTwo = MakeRandomUtil.getBall(6);
                    LinkedList<String> randomThree = MakeRandomUtil.getBall(6);
                    int one = Integer.valueOf(randomOne.get(0));
                    int two = Integer.valueOf(randomTwo.get(0));
                    int three = Integer.valueOf(randomThree.get(0));
                    stringBuffer = new StringBuffer();
                    for (int j = 0; j < count; j++) {
                        if (j == count - 1) {
                            stringBuffer.append(one + two + three);
                        } else {
                            stringBuffer.append(one + two + three + " ");
                        }
                        ballNumber.add(stringBuffer.toString());
                        mode.add(m);
                        numMoney.add("1注 2元");
                        totalNum++;
                    }
                } else if (m.equals("三同号")) {
                    stringBuffer = new StringBuffer();
                    LinkedList<String> threeSameRandomBall = MakeRandomUtil.getBall(6);
                    int threeSameInt = Integer.parseInt(threeSameRandomBall.get(0));
                    for (int j = 0; j < count; j++) {
                        if (j == count - 1) {
                            stringBuffer.append(threeSame[threeSameInt]);
                        } else {
                            stringBuffer.append(threeSame[threeSameInt] + " ");
                        }
                        ballNumber.add(stringBuffer.toString());
                        mode.add(m);
                        numMoney.add("1注 2元");
                        totalNum++;
                    }
                } else if (m.equals("二同号")) {

                    stringBuffer = new StringBuffer();
                    LinkedList<String> twoSameRandomBall = MakeRandomUtil.getBall(30);
                    int twoSameInt = Integer.parseInt(twoSameRandomBall.get(0));
                    for (int j = 0; j < count; j++) {
                        if (j == count - 1) {
                            stringBuffer.append(twoSame[twoSameInt]);
                        } else {
                            stringBuffer.append(twoSame[twoSameInt] + " ");
                        }
                        ballNumber.add(stringBuffer.toString());
                        mode.add(m);
                        numMoney.add("1注 2元");
                        totalNum++;
                    }

                } else if (m.equals("三不同号")) {

                    stringBuffer = new StringBuffer();
                    LinkedList<String> threeDifferentRandomBall = MakeRandomUtil.getBall(20);
                    int threeDifferentInt = Integer.parseInt(threeDifferentRandomBall.get(0));
                    for (int j = 0; j < count; j++) {
                        if (j == count - 1) {
                            stringBuffer.append(threeDifferent[threeDifferentInt]);
                        } else {
                            stringBuffer.append(threeDifferent[threeDifferentInt] + " ");
                        }
                        ballNumber.add(stringBuffer.toString());
                        mode.add(m);
                        numMoney.add("1注 2元");
                        totalNum++;
                    }

                } else if (m.equals("二不同号")) {

                    stringBuffer = new StringBuffer();
                    LinkedList<String> twoDifferentRandomBall = MakeRandomUtil.getBall(15);
                    int twoDifferentInt = Integer.parseInt(twoDifferentRandomBall.get(0));
                    for (int j = 0; j < count; j++) {
                        if (j == count - 1) {
                            stringBuffer.append(twoDifferent[twoDifferentInt]);
                        } else {
                            stringBuffer.append(twoDifferent[twoDifferentInt] + " ");
                        }
                        ballNumber.add(stringBuffer.toString());
                        mode.add(m);
                        numMoney.add("1注 2元");
                        totalNum++;
                    }

                }
                break;
            case LotteryType.KLPK:
                //这里做klpk的任选操作；
                klpkRandom(m, count);
                break;
        }

        adapter.setData(ballNumber, mode, numMoney);
        adapter.notifyDataSetChanged();
        setNumberMoney();
    }

    /**
     * 快乐扑克，根据相应的模式，来生成相应的的注数；
     *
     * @param mode
     * @param number
     */
    private void klpkRandom(String mode, int number) {

        //这里我们要修改的参数有：totalMoney,totalNum,ballNumber,mode,numMoney;
        totalMoney += number * 2;
        totalNum += number;
        for (int i = 0; i < number; i++) {
            List<String> indexType = Arrays.asList(KlpkUtils.indexType);
            int modeIndex = indexType.indexOf(mode);
            int pokerIndex = modeIndex < 5 ? modeIndex : 5;
            int pokerPositionInPokerType = 0;
            String pokerType = "";

            if (modeIndex < 5) {
                //表示对子，同花，顺子，...这里是只能生产一个随机数；

                //这里我们先假设，只有一注；
                if (mode.equals("对子") || mode.equals("豹子")) {

                    pokerPositionInPokerType = (int) (Math.random() * 13 + 1);
                    //随机产生的数字对应牌型；
                    pokerType = KlpkUtils.pokerType[pokerIndex][pokerPositionInPokerType];

                } else if (mode.equals("同花") || mode.equals("同花顺")) {

                    pokerPositionInPokerType = (int) (Math.random() * 4 + 1);
                    //随机产生的数字对应牌型；
                    pokerType = KlpkUtils.pokerType[pokerIndex][pokerPositionInPokerType];

                } else if (mode.equals("顺子")) {

                    pokerPositionInPokerType = (int) (Math.random() * 12 + 1);
                    //随机产生的数字对应牌型；
                    pokerType = KlpkUtils.pokerType[pokerIndex][pokerPositionInPokerType];
                }

            } else {
                //这里表示任选二，任选三.....
                ArrayList<Integer> list = new ArrayList<>();
                int selectSize = modeIndex - 4;

                for (int j = 0; j < selectSize; ) {
                    int randomIndex = (int) (Math.random() * 12 + 1);
                    if (!list.contains(randomIndex)) {
                        list.add(randomIndex);
                    }
                    j = list.size();
                }

                //这里的话，我们要做的一个操作就是将字符串进一个拼接；
                for (Integer integer : list) {
                    pokerType += KlpkUtils.pokerType[pokerIndex][integer] + " ";
                }
                pokerType.trim();
            }

            ballNumber.add(pokerType);
            this.mode.add(mode);
            numMoney.add("1注 2元");
        }

    }


    @Override
    protected void onDestroy() {
        if (timer != null) {
            timer.cancel();
        }
        continueSelect();
        super.onDestroy();
    }


    void showCautionDialog() {
        CautionDialog CautionDialog = new CautionDialog(this, "是否清除本次选号", new OnCautionDialogConfirmListener() {
            @Override
            public void onCancelListener() {
            }

            @Override
            public void onConfirmListener() {
                clearBallInfo(1);
            }
        });
        CautionDialog.show();
    }

    private void clearBallInfo(int code) {
        //防止非空判断导致无法执行清除操作
        Intent intent = new Intent();
        intent.putExtra("Not empty", "Not empty");
        BetConfirmActivity.this.setResult(code, intent);
        BetConfirmActivity.this.finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            showCautionDialog();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        String ns = et_num.getText().toString();
        String ms = et_multiple.getText().toString();

        if (!TextUtils.isEmpty(ns)) {
            if (Integer.parseInt(ns) > 999) {
                ToastUtil.showToast(this, "超出最大投注限额");
                et_num.setText("999");
            } else if (Integer.parseInt(ns) < 1) {
                ToastUtil.showToast(this, "最小为1");
                et_num.setText("1");
            }
            num = Integer.parseInt(et_num.getText().toString());
        } else {
            num = 1;
        }

        if (!TextUtils.isEmpty(ms)) {
            if (Integer.parseInt(ms) > 999) {
                ToastUtil.showToast(this, "超出最大投注限额");
                et_multiple.setText("999");
            } else if (Integer.parseInt(ms) < 1) {
                ToastUtil.showToast(this, "最小为1");
                et_multiple.setText("1");
            }
            multiple = Integer.parseInt(et_multiple.getText().toString());
        } else {
            multiple = 1;
        }

        setNumberMoney();
    }


    //设置注数及金额
    private void setNumberMoney() {
        totalMoney = 0;
        totalNum = 0;
        for (String m : numMoney) {
            try {
                String[] z = m.split("注");
                totalNum += TextUtils.isEmpty(z[0]) ? 0 : Integer.valueOf(z[0]);

                if (cb_add_to.isChecked()) {
                    //这里表示有追加；
                   // totalMoney += TextUtils.isEmpty(z[1]) ? 0 : (Integer.valueOf(z[1].replaceAll("元", "").trim()) + 1);
                } else {
                    //这里表示没有追加
                    //totalMoney += TextUtils.isEmpty(z[1]) ? 0 : Integer.valueOf(z[1].replaceAll("元", "").trim());
                }

            } catch (Exception e) {

            }
        }
        if (cb_add_to.isChecked()) {
            //这里表示有追加；
             totalMoney = totalNum*3;
        } else {
            //这里表示没有追加
            totalMoney = totalNum*2;
        }

        totalMoney = num * totalMoney * multiple;
        tv_number_money.setText(num + "期" + totalNum + "注，总计" + totalMoney + "元");
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == -1) {
            clearBallInfo(-1);
        }
    }

    //item点击
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        continueSelect();
    }

    @Override
    protected void execRandom(Intent intent) {
        super.execRandom(intent);
        //刷新数据
        execData(intent);
        if (adapter != null)
            adapter.notifyDataSetChanged();
        if (ptrLisview != null)
            ptrLisview.onRefreshComplete();
    }
}
